#include "MainWindow.h"
#include "SendDataWorker.h"
#include "ui_MainWindow.h"

#include <QDateTime>
#include <QDebug>
#include <QFile>
#include <QFileDialog>
#include <QStandardItem>
#include <QTableView>
#include <QTextStream>
#include <QThread>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow) {
  ui->setupUi(this);

  m_model = new QStandardItemModel(this);
  ui->tableView->setModel(m_model);

  QThread *thread = new QThread;
  m_worker = new SendDataWorker;
  m_worker->moveToThread(thread);

  connect(this, &MainWindow::sigStart, m_worker, &SendDataWorker::start);
  connect(m_worker, &SendDataWorker::sigSendRow, this, [=](QString msg) {
    QDateTime currentTime = QDateTime::currentDateTime();
    QString formattedTime = currentTime.toString("yyyy-MM-dd HH:mm:ss.zzz");
    qDebug() << formattedTime << " " << msg;
  });
  thread->start();
}

MainWindow::~MainWindow() { delete ui; }

void MainWindow::on_load_clicked() {

  QString filePath = QFileDialog::getOpenFileName(this, "Open CSV file", "",
                                                  "CSV Files (*.csv)");
  if (!filePath.isEmpty()) {

    m_model->clear();
    // 读取 CSV 文件
    QFile file(filePath);
    if (file.open(QIODevice::ReadOnly)) {
      QTextStream in(&file);

      // 读取标题行并设置为模型的列标题
      if (!in.atEnd()) {
        QString headerLine = in.readLine();
        auto headers = headerLine.split(",");
        m_model->setHorizontalHeaderLabels(
            headers.mid(0, 3)); // 只设置前三列的标题
      }

      // 读取数据行
      while (!in.atEnd()) {
        QString line = in.readLine();
        auto items = line.split(",");
        QList<QStandardItem *> standardItemsList;
        for (int i = 0; i < 3; ++i) { // 假设我们只处理前三列
          standardItemsList.append(new QStandardItem(items[i]));
        }
        m_model->appendRow(standardItemsList);
      }
      file.close();
    }
    ui->tableView->resizeColumnsToContents();
    m_worker->setFilePath(filePath);
  }
}

void MainWindow::on_start_clicked() {
  int loopCount = ui->loopCount->value();
  m_worker->setNumLoops(loopCount);
  emit sigStart();
}

void MainWindow::on_stop_clicked() { m_worker->stop(); }
